package com.summer.data.apt;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;

import com.summer.data.annotation.Table;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.model.JavacElements;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.*;

import java.util.Set;

//@SupportedAnnotationTypes("org.summer.data.meta.TableName")
@SupportedAnnotationTypes("*")
//@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class TableProcessor extends AbstractProcessor {

    private Messager messager;
    /**
     * JavacTrees提供了待处理的抽象语法树
     * TreeMaker中了一些操作抽象语法树节点的方法
     * Names提供了创建标识符的方法
     */
    private JavacTrees trees;
    private TreeMaker treeMaker;
    private Names names;
    private JavacElements elementUtils;
    JCTree.JCVariableDecl mapFinderDecl;

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.RELEASE_8;
    }

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);

//        System.out.println(String.format("%s init. ", TableProcessor.class));
        this.messager = processingEnv.getMessager();
        this.trees = JavacTrees.instance(processingEnv);
        Context context = ((JavacProcessingEnvironment) processingEnv).getContext();
        this.treeMaker = TreeMaker.instance(context);
        this.names = Names.instance(context);
        this.elementUtils = (JavacElements)processingEnv.getElementUtils();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
//        System.out.println(String.format("%s process.", TableProcessor.class));

        processTable(roundEnv);

        return false;
    }

    private void processTable(RoundEnvironment roundEnv) {
        Set<? extends Element> annotatedWithTableNameSet = roundEnv.getElementsAnnotatedWith(Table.class);
        for (Element element : annotatedWithTableNameSet) {
//            System.out.println(String.format(" 类 %s 发现注解 %s.", element, Table.class));
            JCTree ast = trees.getTree(element);
            ast.accept(new TableTreeTranslator(messager, trees, treeMaker, names, element));
        }
    }

}


